--- 道胜/海峰 电磁流量计
module(..., package.seeall)
-- 010300000002C40B 读瞬时
-- 010304851F4145135A 12.34
-- 0103007200026410 读累计
-- 01030487DD4145B31E 12.3456
local logtag = "TUF2000"
local cid, uid = 3, 3 -- 默认用3通道
local dtu, udtu = {}, {} -- 配置文件
local meter_ins ,meter_val,addr
function setDtu(dtup, udtup)
    dtu, udtu = dtup, udtup
    addr = udtu.addr and tonumber(udtu.addr) or 1
    if udtu and tonumber(udtu.dtype) == 2 then sys.taskInit(init) end
end
function process(data, status)
    if #data < 8 then return end
    local _t, _v = pack.unpack(data:sub(6,7)..data:sub(4,5), ">f")
    _v = _v and string.format("%.2f",_v) 
    if status == 2 then -- 读顺时
        meter_ins = _v or 0
        lcd.LCD_DATA[3] = '顺时:' .. (meter_ins or "NULL")
    else
        meter_val = _v or 0
        lcd.LCD_DATA[3] = '累计:' .. (meter_val or "NULL")
    end
    usrdata.update({meter_val or 0,meter_ins or 0})
end
function init()
    power.openBoost()
    sys.wait(200)
    local status = 2
    while true do
        -- 读瞬时
        if status==1 then
            status = 2
            tools.modbus_send(uid,addr,3,0,2)
        else
            status = 1
            tools.modbus_send(uid,addr,3,0x72,2)
        end
        result, data = sys.waitUntil('UART_READ_DONE_NEXT_' .. uid, 5000)
        if result then
            if (data) then
                -- log.warn(logtag, '收到串口' .. uid .. '回复数据:', data)
                process(data, status)
            end
            sys.wait(5*1000) -- 5秒切换读取
        else
            lcd.LCD_DATA[3] = logtag.." TIMEOUT"
        end
    end
end
